#include "gateway/beast_http/router.hpp"
#include <mutex>

namespace gateway::beast_http {

void Router::add(const std::string& prefix, const std::string& service) {
    std::unique_lock lk(mutex_);
    routes_.push_back(Route{prefix, service});
    // 保持长前缀优先
    std::sort(routes_.begin(), routes_.end(), [](const Route& a, const Route& b){
        return a.prefix.size() > b.prefix.size();
    });
}

bool Router::load_from_json(const nlohmann::json& routes_array) {
    if (!routes_array.is_array()) return false;
    std::vector<Route> new_routes;
    new_routes.reserve(routes_array.size());
    for (const auto& r : routes_array) {
        if (r.contains("prefix") && r.contains("service")) {
            new_routes.push_back(Route{r["prefix"], r["service"]});
        }
    }
    // 排序
    std::sort(new_routes.begin(), new_routes.end(), [](const Route& a, const Route& b){
        return a.prefix.size() > b.prefix.size();
    });
    // 原子替换
    std::unique_lock lk(mutex_);
    routes_.swap(new_routes);
    return true;
}

std::optional<std::string> Router::match(const std::string& path) const {
    std::shared_lock lk(mutex_);
    for (const auto& r : routes_) {
        if (path.rfind(r.prefix, 0) == 0) {
            return r.service_name;
        }
    }
    return std::nullopt;
}

} // namespace gateway::beast_http
